﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace BankService
{
    internal sealed class StreamUtil
    {
        private StreamUtil()
        {
        }

        public static bool Serialize(object graph, string fileName)
        {
            try
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                using (FileStream fs = File.Create(fileName))
                {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fs, graph);
                    fs.Close();
                }
            }
            catch
            {
            }
            return false;
        }

        public static T Deserialize<T>(string fileName)
        {
            try
            {
                if (File.Exists(fileName))
                {
                    using (FileStream fs = File.OpenRead(fileName))
                    {
                        return StreamUtil.Deserialize<T>(fs);
                    }
                }
            }
            catch
            {
            }
            return default(T);
        }

        public static T Deserialize<T>(Stream stream)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                return (T)formatter.Deserialize(stream);
            }
            catch
            {
                // do nothing, just ignore any possible errors
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }

            }
            return default(T);
        }
    }
}
